package com.zy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zy.dto.Result;
import com.zy.dto.UserDTO;
import com.zy.entity.Follow;
import com.zy.mapper.FollowMapper;
import com.zy.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zy.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 张宇
 * @since 2024-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserServiceImpl userService;

    @Override
    public Result follow(Long followUserId, Boolean isFollow) {
        // 1.关注
        Long userId = UserHolder.getUser().getId();
        if(isFollow){
            // 1.1新增数据
            Follow follow = Follow.builder()
                    .userId(userId)
                    .followUserId(followUserId)
                    .build();
            boolean isSuccess = save(follow);
            if(isSuccess){
                // 1.2将关注用户的id，放入redis的set集合 sadd userId followUserId
                redisTemplate.opsForSet().add("follows:" + userId, followUserId.toString());
                return Result.ok();
            }
        }
        // 2. 取消关注
        // 2.1 删除数据
        boolean isSuccess = remove(new QueryWrapper<Follow>().eq("user_id", userId).eq("follow_user_id", followUserId));
        // 3.把关注的redis用户从集合中移除
        if(isSuccess){
            redisTemplate.opsForSet().remove("follows:" + userId, followUserId.toString());
        }
        return Result.ok();
    }

    @Override
    public Result isFollow(Long followUserId) {
        Long userId = UserHolder.getUser().getId();
        Integer isFollow =  query().eq("user_id", userId).eq("follow_user_id", followUserId).count();
        // TODO 值得学习
        return Result.ok(isFollow > 0);

    }

    @Override
    public Result followCommons(Long id) {
        Long userId = UserHolder.getUser().getId();
        Set<String> followsCommons = redisTemplate.opsForSet().intersect("follows:" + userId, "follows:" + id);
        if(followsCommons == null || followsCommons.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        List<Long> list = followsCommons.stream().map(Long::valueOf).collect(Collectors.toList());
        List<UserDTO> follows = userService.listByIds(list).stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class)).collect(Collectors.toList());
        return Result.ok(follows);
    }
}
